﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.Reflection;

namespace ASoft.Service
{
    public class ExcelService
    {
        HSSFWorkbook workbook;
        ISheet sheet;
        public ExcelService()
        {
            workbook = new HSSFWorkbook();
            sheet = workbook.CreateSheet("Sheet1");
        }
        public Stream Export(List<object> objs, Dictionary<string, string> headerInfo)
        {

            CreateHeader(headerInfo);
            CreateBody(objs, headerInfo);

            MemoryStream ms = new MemoryStream();
            workbook.Write(ms);
            return ms;
        }

        private void CreateBody(List<object> objs, Dictionary<string, string> headerInfo)
        {
            if (objs == null || objs.Count == 0)
            {
                return;
            }

            var ps = headerInfo.Keys.ToList();

            for (int i = 0; i < objs.Count; i++)
            {
                IRow dataRow = sheet.CreateRow(i + 1);
                for (int j = 0; j < ps.Count; j++)
                {
                    var value = objs[i].GetType().GetProperty(ps[j], BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase)
                        .GetValue(objs[i], null);
                    if (value != null)
                        dataRow.CreateCell(j).SetCellValue(value.ToString());
                }
            }
        }

        public void Export(List<object> objs, Dictionary<string, string> headerInfo, string filepath)
        {
            var stream = Export(objs, headerInfo);
            using (var fs = File.Open(filepath, FileMode.Create))
            {
                stream.Position = 0;
                stream.CopyTo(fs);
            }
        }

        private void CreateHeader(Dictionary<string, string> headerInfo)
        {
            IRow dataRow = sheet.CreateRow(0);
            dataRow.Height = (short)400;
            int i = 0;
            foreach (var kv in headerInfo)
            {
                dataRow.CreateCell(i).SetCellValue(kv.Value);
                i++;
            }
        }
    }
}
